package com.weiyi.servlet03;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
 * 
 * @description 使用part方式上传文件1
 * @author 惟一
 * @date 2020年6月26日下午5:55:37
 */
@MultipartConfig
@WebServlet("/upload1.do")
public class UploadDemo1 extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Part part = req.getPart("photo");
		String filename = getFilename(part);
		writeTo(filename,part);
		
		
	}

	private void writeTo(String filename, Part part) throws IOException {
		InputStream in = part.getInputStream();
		FileOutputStream out = new FileOutputStream("F:\\"+filename);
		byte[] buffer = new byte[1024];
		int len = -1;
		while((len = in.read(buffer)) != -1) {
			out.write(buffer, 0, len);			
		}		
	}

	private String getFilename(Part part) {
		String header = part.getHeader("Content-Disposition");
		String filename = header.substring((header.indexOf("filename=\"")+10),header.lastIndexOf("\""));
		return filename;
	}
}
